/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * UpdateServerHandler.java
 * servermgr
 * 2014年1月20日下午5:02:16
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.net.update;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.gson.Gson;



@Component
@io.netty.channel.ChannelHandler.Sharable
public class UpdateServerHandler extends ChannelInboundHandlerAdapter {

	
	static final Log logger = LogFactory.getLog(UpdateServerHandler.class);

	private ByteBuf buffer;
	
	
	@Value("${apphomedir}")
	private String apphomedir;
	
	@Value("${nwhomedir}")
	private String nwhomedir;
	
	@Value("${updateFromHost}")
	private String updateFromHost;
	
	@Value("${nwpath}")
	private String nwpath;
	
	@Value("${apppath}")
	private String apppath;
	
	private static int appfrom;
	private static int nwfrom;
	
	@PostConstruct
	public void inti(){
		appfrom = IOUtils.fromPos(apphomedir);
        nwfrom  = IOUtils.fromPos(nwhomedir);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
					
			ByteBuf b = (ByteBuf) msg;
			buffer.writeBytes(b);
			b.release();
			byte[] datas = new byte[buffer.readableBytes()];
			buffer.readBytes(datas);
			
			String json = new String(datas);
			logger.info("updated request  "+json);
			Gson gson = new Gson();
			UpdateFlag uf = gson.fromJson(json, UpdateFlag.class);			
			uf.setUpdated(Boolean.TRUE);
			uf.setFromHost(updateFromHost);	
			uf.setAppPath(apppath);
			uf.setNwPath(nwpath);
			List<String> files = Lists.newArrayList();
			IOUtils.checkFile(appfrom, new File(apphomedir), files,IOUtils.NW_EXCLUSIVE);
			logger.info("The fllowing appdata files will be updated "+files.size());			
			uf.setUpfiles(files);

			List<String> nwfiles = Lists.newArrayList();
			IOUtils.checkFile(nwfrom, new File(nwhomedir), nwfiles);
			uf.setNwfiles(nwfiles);
			logger.info("the fllowing nw      files will be updated : "+nwfiles.size());
			
			json = gson.toJson(uf);
	        //logger.info(json);
			ByteBuf wbuf  = ctx.alloc().buffer();
			wbuf.writeBytes(json.getBytes());
		    ctx.write(wbuf);
		    ctx.flush();
		    ctx.close();

	}
	
	

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		 ctx.flush();
	}



	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		buffer = ctx.alloc().buffer();
	}



	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		 buffer.release();
		 buffer = null;
	}



	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	
}
